package com.jiao.table.lua;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.file.FileReader;
import com.jiao.support.script.LuaScriptText;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * lua 脚本加载.
 * @Author: vincent.jiao
 * @Date: 2021/5/31
 */
public class LuaScriptLoad {
    private static Map<String, String> fileAndContentMap = new HashMap<>();
    private static Set<LuaSyntaxEnhance> syntaxEnhanceSet = new HashSet<>();
    private static LuaScriptLoad luaLoad = new LuaScriptLoad();

    private LuaScriptLoad() {
        ClassPathResource pathResource = new ClassPathResource("redis");
        try {
            File file = pathResource.getFile();
            File[] subFile = file.listFiles();
            if(subFile.length > 0){
                for (File item : subFile){
                    FileReader fileReader = new FileReader(item.getAbsolutePath());
                    String script = fileReader.readString();
                    fileAndContentMap.put(item.getName(), script);
                }
            }

        } catch (FileNotFoundException e) {
            if(CollectionUtil.isEmpty(fileAndContentMap)) {
                //如果根目录下没有加载到文件，那就加载内部的
                fileAndContentMap.put("addCacheData.lua", CacheExceScriptText.getAddCacheData());
                fileAndContentMap.put("delCacheData.lua", CacheExceScriptText.getDelCacheData());
                fileAndContentMap.put("updCacheData.lua", CacheExceScriptText.getUpdCacheData());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void syntaxEnhance(){
        if (CollectionUtil.isEmpty(syntaxEnhanceSet)){
            return;
        }

        if (CollectionUtil.isEmpty(fileAndContentMap)){
            return;
        }

        for(String item : fileAndContentMap.keySet()){
            for(LuaSyntaxEnhance syntaxEnhance : syntaxEnhanceSet){
                fileAndContentMap.put(item, syntaxEnhance.syntaxEnhance(fileAndContentMap.get(item)));
            }
        }
    }

    public static LuaScriptLoad getInstance(){
        return luaLoad;
    }

    public void setSyntaxEnhance(LuaSyntaxEnhance luaSyntaxEnhance){
        syntaxEnhanceSet.add(luaSyntaxEnhance);
    }

    public static Map<String, String> getFileAndContentMap(){
        return fileAndContentMap;
    }
}
